class Solution
{
public:
    int minimumDiameterAfterMerge(vector<vector<int>> &edges1, vector<vector<int>> &edges2)
    {
        auto maxLen = [](const vector<vector<int>> &edges)
        {
            int n = edges.size() + 1;
            vector<vector<int>> graph(n);
            for (auto &edge : edges)
            {
                graph[edge[0]].push_back(edge[1]);
                graph[edge[1]].push_back(edge[0]);
            }
            int maxL = 0;
            int maxNode = 0;
            function<void(int, int, int)> dfs = [&](int node, int len, int parent)
            {
                if (len > maxL)
                {
                    maxL = len;
                    maxNode = node;
                }
                for (int next : graph[node])
                {
                    if (next != parent)
                    {
                        dfs(next, len + 1, node);
                    }
                }
            };
            dfs(0, 0, -1);
            dfs(maxNode, 0, -1);
            return maxL;
        };
        int l1 = maxLen(edges1);
        int l2 = maxLen(edges2);
        int l = (l1 + 1) / 2 + (l2 + 1) / 2 + 1;
        return max({l1, l2, l});
    }
};